package io.xxx.omni.osc.domain

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.common.dateTimeFormatPattern
import io.xxx.omni.osc.common.toLocalDateTime
import org.hibernate.Hibernate
import org.springframework.data.jpa.repository.JpaRepository
import java.time.LocalDateTime
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id

/**
 * 爱库存活动信息
 */
@Entity
data class AkcActivity(
    @Id
    val id: String,
    val name: String,
    val sid: String,
    val beginTime: LocalDateTime,
    val endTime: LocalDateTime,
    val data: String,
    val completed: Boolean,
) {
    constructor(store: Store, jsonObject: JSONObject) : this(
        jsonObject.getString("id"),
        jsonObject.getString("name"),
        store.id,
        jsonObject.getString("begintime").toLocalDateTime(),
        jsonObject.getString("endtime").toLocalDateTime(),
        jsonObject.toJSONString(),
        false
    )

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false
        other as AkcActivity
        return id == other.id
    }

    override fun hashCode(): Int = 484779935

    override fun toString(): String {
        return JSON.toJSONStringWithDateFormat(this, dateTimeFormatPattern)
    }
}

interface AkcActivityRepository : JpaRepository<AkcActivity, String> {

    fun findBySidAndCompleted(sid: String, completed: Boolean): List<AkcActivity>
}